#include <opencv2/opencv.hpp>
#include <iostream>
#include <RMVideoCapture.h>

//#define GALAXY

#ifdef GALAXY
#include "GxIAPI.h"
#include "DxImageProc.h"
#endif
using namespace cv;
using namespace std;
int iLowH = 83;int iHighH = 107;
int jLowH = 83;int jHighH = 107;
int iLowS = 0;int iHighS = 255;
int iLowV = 230;int iHighV = 255;



#ifdef GALAXY
class CameraDevice
{
public:
    CameraDevice();
    ~CameraDevice();
    int init();
    void getImage(Mat &img);
    uint64_t getFrameNumber();
private:
    GX_STATUS status;
    GX_DEV_HANDLE hDevice;
    GX_OPEN_PARAM stOpenParam;
    uint32_t nDeviceNum;
    GX_FRAME_DATA stFrameData;
    Mat src;
    uint64_t nFrameNum;
};

#endif
Mat src;
int dx = 0;

//    int ddx = 0;
char ad[128] = {0};
void on_mouse(int event,int x,int y,int flags,void *ustc)
{
    switch(event)
    {
    case CV_EVENT_LBUTTONDOWN:
    {
        Mat img;
        src.copyTo(img);
        sprintf(ad,"/home/cz/Pictures/gjj/chessboard%02d.jpg", ++dx);
        //imshow(ad, src);
        imwrite(ad,img);
        cout<<"saved"<<endl;
    }break;
    case CV_EVENT_MOUSEMOVE:
    {

    }break;
    case EVENT_LBUTTONUP:
    {

    }
    }
}
int main(int argc,char** argv)
{


    //int dx = 0;

    int ddx = 0;
    //    char ad[128] = {0};
    cv::namedWindow("Control");
    cv::namedWindow("src",CV_WINDOW_NORMAL);
    cvCreateTrackbar("LowH", "Control", &iLowH, 255); //Hue (0 - 179)
    cvCreateTrackbar("HighH", "Control", &iHighH, 255);
    cvCreateTrackbar("jLowH", "Control", &jLowH, 255); //Hue (0 - 179)
    cvCreateTrackbar("jHighH", "Control", &jHighH, 255);
    cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
    cvCreateTrackbar("HighS", "Control", &iHighS, 255);
    cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
    cvCreateTrackbar("HighV", "Control", &iHighV, 255);
    setMouseCallback("src",on_mouse);
    //115 is hight
    //20 is low
#ifdef GALAXY
    CameraDevice cap;
    cap.init();
#else
    RMVideoCapture cap("/dev/video1", 3);
    cap.setVideoFormat(640, 360, 1);
    int exp_t = 100;
    cap.setExposureTime(0, exp_t);//settings->exposure_time);
    cap.startStream();
    cap.info();
#endif

    while(1){
        //        Mat src;
#ifdef GALAXY
        cap.getImage(src);
#else
        cap >> src;
#endif
        Mat imgHSV, mask;
        cvtColor(src, imgHSV, COLOR_BGR2HSV);
        //        inRange(imgHSV, Scalar(iLowH,iLowS,iLowV), Scalar(iHighH,iHighS,iHighV), mask1);
        if(0){
            //blue
            //inRange(imgHSV, Scalar(61, 0 ,218), Scalar(126, 182, 255), mask); //Threshold the image
            //inRange(imgHSV,Scalar(60,0,235), Scalar(140, 255, 255),mask);//680x480
            inRange(imgHSV,Scalar(iLowH,iLowS,iLowV), Scalar(iHighH,iHighS,iHighV),mask);//680x480

            //inRange(imgHSV,Scalar(107,0,39), Scalar(135, 255, 255),mask);
        }
        else{
            //red
            Mat1b mask1, mask2;
            inRange(imgHSV, Scalar(iLowH,iLowS,iLowV), Scalar(iHighH,iHighS,iHighV), mask1);
            inRange(imgHSV, Scalar(jLowH,iLowS,iLowV), Scalar(jHighH,iHighS,iHighV), mask2);
            mask = mask1| mask2;
        }
        //        imshow("hsv", mask);

        char key = waitKey(1);
        bool save_flag = false;
        switch(key)
        {

        case 'm':
            save_flag = true;
            break;

        case 'a':
            sprintf(ad,"/home/cz/Pictures/galaxy_1024/chessboard%02d.jpg", ++dx);
            //imshow(ad, src);
            imwrite(ad,src);
            cout<<"saved"<<endl;
            break;
        case 'q':
            return -1;
        }
        //        if(save_flag)
        //        {
        //            sprintf(ad,"/home/cz/Pictures/galaxy_1/chessboard%02d.jpg", ++ddx);
        //            //imshow(ad, src);
        //            imwrite(ad,src);
        //        }
        putText(src, to_string(dx), Point(280,260), FONT_HERSHEY_SIMPLEX, 8, Scalar(255,255,255), 6);
        imshow("src", src);
    }
}


#ifdef GALAXY
CameraDevice::CameraDevice()
{
    status = GX_STATUS_SUCCESS;
    //    GX_DEV_HANDLE hDevice = nullptr;
    //    uint32_t nDeviceNum = 0;
    src.create(480,640,CV_8UC3);
    //    src.create(1024,1280,CV_8UC3);
    stOpenParam.accessMode = GX_ACCESS_EXCLUSIVE;
    stOpenParam.openMode   = GX_OPEN_INDEX;
    stOpenParam.pszContent = "1";
    nFrameNum = 0;

}

CameraDevice::~CameraDevice()
{
    status = GXSendCommand(hDevice, GX_COMMAND_ACQUISITION_STOP);

    //释放图像缓冲区buffer
    free(stFrameData.pImgBuf);

    status = GXCloseDevice(hDevice);
    status = GXCloseLib();
}

int CameraDevice::init()
{
    // 初始化库
    status = GXInitLib();

    if (status != GX_STATUS_SUCCESS)
    {
        return 0;
    }
    status = GXUpdateDeviceList(&nDeviceNum, 1000);

    if ((status != GX_STATUS_SUCCESS) || (nDeviceNum <= 0))
    {
        return 0;
    }
    status = GXOpenDevice(&stOpenParam, &hDevice);
    std::cout << status << std::endl;
    if (status == GX_STATUS_SUCCESS)
    {
        int64_t nPayLoadSize = 0;
        //获取图像buffer大小，下面动态申请内存
        status = GXGetInt(hDevice, GX_INT_PAYLOAD_SIZE, &nPayLoadSize);

        if (status == GX_STATUS_SUCCESS && nPayLoadSize > 0)
        {
            //定义GXGetImage的传入参数

            //根据获取的图像buffer大小m_nPayLoadSize申请buffer
            stFrameData.pImgBuf = malloc((size_t)nPayLoadSize);

            // 设置曝光值
            status = GXSetFloat(hDevice, GX_FLOAT_EXPOSURE_TIME, 30000);

            //设置采集模式连续采集
            //            status = GXSetEnum(hDevice, GX_ENUM_ACQUISITION_MODE, GX_ACQ_MODE_CONTINUOUS);
            //            status = GXSetInt(hDevice, GX_INT_ACQUISITION_SPEED_LEVEL, 1);
            //            status = GXSetEnum(hDevice, GX_ENUM_BALANCE_WHITE_AUTO, GX_BALANCE_WHITE_AUTO_CONTINUOUS);

            //发送开始采集命令
            status = GXSendCommand(hDevice, GX_COMMAND_ACQUISITION_START);
            return 1;
        }
    }
    return 0;
}

void CameraDevice::getImage(Mat &img)
{
    GXGetImage(hDevice, &stFrameData, 100);
    //usleep(1);

    if (stFrameData.nStatus == GX_FRAME_STATUS_SUCCESS)
    {
        //图像获取成功

        double t1 = getTickCount();
        char* m_rgb_image=nullptr; //增加的内容
        m_rgb_image=new char[stFrameData.nWidth*stFrameData.nHeight*3];

        //                        memcpy(src.data,stFrameData.pImgBuf,stFrameData.nWidth*stFrameData.nHeight);

        DxRaw8toRGB24(stFrameData.pImgBuf,m_rgb_image,stFrameData.nWidth, stFrameData.nHeight,RAW2RGB_NEIGHBOUR3,DX_PIXEL_COLOR_FILTER(BAYERBG),false);

        memcpy(src.data,m_rgb_image,stFrameData.nWidth*stFrameData.nHeight*3);

        src.copyTo(img);
        nFrameNum++;
        //                        imshow("test",src);

        //对图像进行处理...
        delete []m_rgb_image;
        //                        }
    }
}

uint64_t CameraDevice::getFrameNumber()
{
    return nFrameNum;
}

#endif



